package logic

import (
	"collection_srv/collection"
	"collection_srv/internal/dao"
	"collection_srv/internal/svc"
	"collection_srv/model"
	"context"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"os"
	"smart-health-platforms/config"
	"smart-health-platforms/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type ThermometerHealthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewThermometerHealthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ThermometerHealthLogic {
	return &ThermometerHealthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 体温生成报告
func (l *ThermometerHealthLogic) ThermometerHealth(in *collection.ThermometerHealthRequest) (*collection.ThermometerHealthResponse, error) {
	// todo: add your logic here and delete this line
	userID := in.UserId
	// 报告保存目录（不存在会自动创建）
	reportDir := config.AppCong.NaCos.Address // 可自定义路径，如 "/data/reports"
	// 生成并保存报告
	_, lu, err := dao.GenerateAndSaveReport(uint64(userID), reportDir, "result_data")
	if err != nil {
		// 处理错误（如查询失败、文件写入失败等）
		pkg.Error("生成报告失败: %v\n", zap.Error(err))
	}
	jsonFile := lu
	data, err := os.ReadFile(jsonFile)
	if err != nil {
		fmt.Printf("读取文件失败: %v\n", err)
		pkg.Error("读取文件失败: %v\n", zap.Error(err))
	}
	// 2. 解析JSON数据
	var report model.HealthReport
	if err := json.Unmarshal(data, &report); err != nil {
		fmt.Printf("解析JSON失败: %v\n", err)
		pkg.Error("解析JSON失败: %v\n", zap.Error(err))
	}
	// 3. 创建转换器并生成Excel
	converter := dao.NewExcelConverter(&report)
	filePath, err := converter.ConvertToExcel("reports")
	if err != nil {
		fmt.Printf("生成Excel失败: %v\n", err)
		pkg.Error("生成Excel失败: %v\n", zap.Error(err))
	}
	fmt.Printf("Excel报表已生成: %s\n", filePath)
	return &collection.ThermometerHealthResponse{Msg: "生成报告成功"}, nil
}
